package com.rw.engine.ip.resolver;

import com.rw.engine.ip.anno.IpParam;
import com.rw.engine.ip.interceptor.IpGetter;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 * IP参数解析器
 */
public class IpArgumentResolver implements HandlerMethodArgumentResolver {
    private final IpGetter ipGetter;

    /**
     * 设置获取IP的方法
     *
     * @param ipGetter ip获取方法
     */
    public IpArgumentResolver(IpGetter ipGetter) {
        this.ipGetter = ipGetter;
    }

    public IpArgumentResolver() {
        this.ipGetter = ServletRequest::getRemoteAddr;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // 如果参数前面有@IpParam注解，并且参数类型是String，则返回true
        return parameter.hasParameterAnnotation(IpParam.class) &&
                parameter.getParameterType().isAssignableFrom(String.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        HttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class);
        if (req == null) {
            return null;
        }

        return ipGetter == null ? req.getRemoteAddr() : ipGetter.getIp(req);
    }
}
